#include "StdAfx.h"
#include "DxIndexBuffer.h"
#include "DxRenderer.h"


DxIndexBuffer::DxIndexBuffer(void)
{
	m_pIndexBuffer = 0;
	m_pLockPointer = 0;
	m_bLocked = false;
}


DxIndexBuffer::~DxIndexBuffer(void)
{
	if( m_pIndexBuffer )
		m_pIndexBuffer->Release();
}

/**
 * Creates a new index buffer
 * BRF 05/10/11
 **/
bool DxIndexBuffer::CreateIndexBuffer(int iLength)
{
	if( FAILED(DxRenderer::GetInstance()->GetDevice()->CreateIndexBuffer(iLength * sizeof(u16), 0,
		D3DFMT_INDEX16, D3DPOOL_MANAGED, &m_pIndexBuffer, NULL)))
	{
		m_pIndexBuffer = 0;
		return false;
	}

	m_iPrimCount = iLength / 3;

	return true;

}

/**
 * Locks the index buffer so it can be accessed
 * BRF 05/11/11
 **/
bool DxIndexBuffer::Lock()
{
	if( !m_bLocked )
	{
		if( m_pIndexBuffer->Lock(0, 0, (void**)&m_pLockPointer, 0) == D3D_OK)		
			m_bLocked = true;
	}

	return m_bLocked;
}

/**
 * Unlocks the index buffer so it can be used to draw the geometry
 * BRF 05/11/11
 **/
bool DxIndexBuffer::UnLock()
{
	if( m_bLocked )
	{
		if( m_pIndexBuffer->Unlock() == D3D_OK )
			m_bLocked = false;
	}

	return !m_bLocked;
}

/**
 * Fills the index buffer with an array of indices
 * BRF 05/11/11
 **/
void DxIndexBuffer::SetIndices(FixedArray<u16> * indices)
{
	if( m_bLocked )
	{
		for(int i = 0; i < indices->GetNumElements(); i++)
		{
			m_pLockPointer[i] = (*indices)[i];
		}
	}
}